
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Plus, Trash2, SlidersHorizontal, Info, RefreshCw, Calculator, Lightbulb, CheckCircle, ArrowRight, Wrench, Users, Truck, Clock, Edit } from 'lucide-react';
import { InvokeLLM } from "@/api/integrations";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";

const FactorRuleEditor = ({ title, rules = [], onUpdate, unit, description, isAngle = false, activeRuleIndex }) => {
  const handleUpdate = (index, field, value) => {
    const newRules = [...rules];
    newRules[index][field] = parseFloat(value) || 0;
    onUpdate(newRules);
  };

  const addRule = () => {
    onUpdate([...rules, { threshold: 0, multiplier: 1.0 }]);
  };

  const removeRule = (index) => {
    onUpdate(rules.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-2 rounded-lg bg-gray-50 p-4 border">
      <div className="flex justify-between items-center mb-2">
        <div>
          <Label className="font-semibold text-gray-800">{title}</Label>
          <p className="text-xs text-gray-500">{description}</p>
        </div>
        <Button type="button" size="sm" variant="outline" onClick={addRule}>
          <Plus className="w-3 h-3 mr-1"/>添加规则
        </Button>
      </div>
      <div className="grid grid-cols-[auto,1fr,1fr,auto] gap-2 text-sm font-medium text-gray-600 px-2 items-center">
        <span></span>
        <span>阈值 ({isAngle ? '<' : '>'} {unit})</span>
        <span>乘数</span>
        <span>操作</span>
      </div>
      {rules.map((rule, index) => (
        <div 
          key={index} 
          className={`grid grid-cols-[auto,1fr,1fr,auto] items-center gap-2 p-1 rounded-md transition-all ${index === activeRuleIndex ? 'bg-blue-100 border-l-4 border-blue-500' : ''}`}
        >
          <div className="w-6 h-6 flex items-center justify-center">
            {index === activeRuleIndex && <CheckCircle className="w-4 h-4 text-blue-600" />}
          </div>
          <Input
            type="number"
            value={rule.threshold || 0}
            onChange={e => handleUpdate(index, 'threshold', e.target.value)}
          />
          <Input
            type="number"
            step="0.1"
            value={rule.multiplier || 0}
            onChange={e => handleUpdate(index, 'multiplier', e.target.value)}
          />
          <Button type="button" variant="ghost" size="icon" className="text-red-500" onClick={() => removeRule(index)}>
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
      ))}
    </div>
  );
};

const TypeFactorEditor = ({ title, multipliers = [], onUpdate, description, activeType }) => {
  const crossingTypes = ["highway", "railway", "river", "cable", "pipeline", "building", "forest", "other", "mountain", "urban", "farm"];

  const handleUpdate = (type, value) => {
    const newMultipliers = [...multipliers];
    const existing = newMultipliers.find(m => m.type === type);
    if (existing) {
      existing.multiplier = parseFloat(value) || 1.0;
    } else {
      newMultipliers.push({ type, multiplier: parseFloat(value) || 1.0 });
    }
    onUpdate(newMultipliers);
  };

  return (
    <div className="space-y-2 rounded-lg bg-gray-50 p-4 border">
      <div>
        <Label className="font-semibold text-gray-800">{title}</Label>
        <p className="text-xs text-gray-500">{description}</p>
      </div>
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-2">
        {crossingTypes.map(type => (
          <div key={type} className={`p-2 rounded-md transition-all ${type === activeType ? 'bg-blue-100 border border-blue-300' : ''}`}>
             <div className="flex items-center gap-2">
                {type === activeType && <ArrowRight className="w-3 h-3 text-blue-600" />}
                <Label className="text-sm font-medium capitalize">{type}</Label>
            </div>
            <Input
              type="number"
              step="0.1"
              value={multipliers.find(m => m.type === type)?.multiplier || 1.0}
              onChange={e => handleUpdate(type, e.target.value)}
            />
          </div>
        ))}
      </div>
    </div>
  );
};

// 新增：用于简化主界面的弹出式规则编辑器
const FactorRulePopoverEditor = ({ title, description, unit, isAngle, activeRuleIndex, rules, onUpdate, currentMultiplier, currentValue, appliedRule }) => {
  return (
    <div className="flex items-center justify-between p-3 border rounded-lg bg-white shadow-sm hover:bg-gray-50/50 transition-colors">
      <div>
        <div className="flex items-baseline gap-2">
          <Label className="font-semibold text-gray-900">{title}</Label>
          {(currentValue !== undefined && currentValue !== null) && (
            <span className="text-xs font-medium text-gray-600">
              (当前输入值: <span className="font-bold text-blue-600">{currentValue} {unit}</span>
              {appliedRule && `, 适用规则: ${isAngle ? '<' : '>'} ${appliedRule.threshold}${unit}`}
              )
            </span>
          )}
        </div>
        <p className="text-xs text-gray-500 mt-1">{description}</p>
      </div>
      <div className="flex items-center gap-4">
        <div className="text-right">
            <span className="text-2xl font-bold text-blue-600">x {currentMultiplier.toFixed(2)}</span>
            <p className="text-xs text-gray-500">当前建议值</p>
        </div>
        <Popover>
          <PopoverTrigger asChild>
            <Button variant="outline" size="sm"><Edit className="w-3 h-3 mr-1" /> 编辑规则</Button>
          </PopoverTrigger>
          <PopoverContent className="w-96 p-0">
            <FactorRuleEditor 
              title={title}
              rules={rules}
              onUpdate={onUpdate}
              unit={unit}
              description={description}
              isAngle={isAngle}
              activeRuleIndex={activeRuleIndex}
            />
          </PopoverContent>
        </Popover>
      </div>
    </div>
  );
};

const TypeFactorPopoverEditor = ({ title, description, activeType, multipliers = [], onUpdate, currentMultiplier, currentValue }) => {
    return (
    <div className="flex items-center justify-between p-3 border rounded-lg bg-white shadow-sm hover:bg-gray-50/50 transition-colors">
      <div>
        <div className="flex items-baseline gap-2">
          <Label className="font-semibold text-gray-900">{title}</Label>
          {currentValue && (
            <span className="text-xs font-medium text-gray-600">
              (当前输入值: <span className="font-bold text-blue-600 capitalize">{currentValue}</span>)
            </span>
          )}
        </div>
        <p className="text-xs text-gray-500 mt-1">{description}</p>
      </div>
      <div className="flex items-center gap-4">
        <div className="text-right">
            <span className="text-2xl font-bold text-blue-600">x {currentMultiplier.toFixed(2)}</span>
            <p className="text-xs text-gray-500">当前建议值</p>
        </div>
        <Popover>
          <PopoverTrigger asChild>
            <Button variant="outline" size="sm"><Edit className="w-3 h-3 mr-1" /> 编辑规则</Button>
          </PopoverTrigger>
          <PopoverContent className="w-[450px] p-0">
            <TypeFactorEditor 
              title={title}
              multipliers={multipliers}
              onUpdate={onUpdate}
              description={description}
              activeType={activeType}
            />
          </PopoverContent>
        </Popover>
      </div>
    </div>
  );
}


export default function FactorEditor({ scheme, crossingPoint, onUpdate }) {
  const [isRecommending, setIsRecommending] = useState(false);
  const [lastRecommendation, setLastRecommendation] = useState(null);
  const [currentFactorPreview, setCurrentFactorPreview] = useState(null);

  // Local state to manage engineeringFactors, synced from scheme prop
  const [localFactors, setLocalFactors] = useState({});

  // Effect to synchronize scheme.engineeringFactors with localFactors
  useEffect(() => {
    // 🔍 自检点9: FactorEditor接收到的数据
    console.log('🔍 自检点9 - FactorEditor收到的scheme.engineeringFactors:', scheme?.engineeringFactors);
    console.log('🔍 自检点9 - 数据类型:', typeof scheme?.engineeringFactors);
    
    // Define a default structure for engineeringFactors to ensure all rule arrays exist
    const defaultEngineeringFactors = {
      spanFactorRules: [],
      heightFactorRules: [],
      nettingFactorRules: [],
      angleFactorRules: [],
      widthFactorRules: [],
      typeFactorMultipliers: []
    };

    if (scheme?.engineeringFactors && typeof scheme.engineeringFactors === 'object') {
      console.log('🔍 自检点9 - 有效的engineeringFactors数据，开始合并');
      
      // 深度合并，确保知识库中的规则数据被正确应用
      const mergedFactors = {
        ...defaultEngineeringFactors,
        // 确保每个规则数组都被正确处理
        spanFactorRules: Array.isArray(scheme.engineeringFactors.spanFactorRules) ? 
          [...scheme.engineeringFactors.spanFactorRules] : defaultEngineeringFactors.spanFactorRules,
        heightFactorRules: Array.isArray(scheme.engineeringFactors.heightFactorRules) ? 
          [...scheme.engineeringFactors.heightFactorRules] : defaultEngineeringFactors.heightFactorRules,
        nettingFactorRules: Array.isArray(scheme.engineeringFactors.nettingFactorRules) ? 
          [...scheme.engineeringFactors.nettingFactorRules] : defaultEngineeringFactors.nettingFactorRules,
        angleFactorRules: Array.isArray(scheme.engineeringFactors.angleFactorRules) ? 
          [...scheme.engineeringFactors.angleFactorRules] : defaultEngineeringFactors.angleFactorRules,
        widthFactorRules: Array.isArray(scheme.engineeringFactors.widthFactorRules) ? 
          [...scheme.engineeringFactors.widthFactorRules] : defaultEngineeringFactors.widthFactorRules,
        typeFactorMultipliers: Array.isArray(scheme.engineeringFactors.typeFactorMultipliers) ? 
          [...scheme.engineeringFactors.typeFactorMultipliers] : defaultEngineeringFactors.typeFactorMultipliers
      };
      
      // 🔍 自检点10: 合并完成的数据
      console.log('🔍 自检点10 - 合并后的工程系数数据:', mergedFactors);
      console.log('🔍 自检点10 - spanFactorRules数量:', mergedFactors.spanFactorRules?.length);
      console.log('🔍 自检点10 - heightFactorRules数量:', mergedFactors.heightFactorRules?.length);
      
      setLocalFactors(mergedFactors);
    } else {
      console.log('🔍 自检点9 - scheme.engineeringFactors 不存在或无效，使用默认结构');
      setLocalFactors(defaultEngineeringFactors);
    }
  }, [scheme?.engineeringFactors]); // Re-run when the engineeringFactors prop changes

  // 计算当前生效的系数
  useEffect(() => {
    if (!localFactors || !crossingPoint) {
      setCurrentFactorPreview(null);
      return;
    }

    console.log('FactorEditor: 计算系数预览，使用 localFactors:', localFactors);
    
    const calculatedFactors = calculateCurrentFactors({
      spanLength: crossingPoint.spanLength,
      crossingHeight: crossingPoint.crossingHeight,
      crossedObjectWidth: crossingPoint.crossedObjectWidth,
      crossingAngle: crossingPoint.crossingAngle,
      calculatedNettingLength: scheme.calculatedNettingLength,
      crossingType: crossingPoint.crossingType
    }, localFactors);

    console.log('FactorEditor: 计算得到的系数预览:', calculatedFactors);
    setCurrentFactorPreview(calculatedFactors);
  }, [localFactors, crossingPoint, scheme?.calculatedNettingLength]);

  const calculateCurrentFactors = (params, rules) => {
    const { spanLength, crossingHeight, crossedObjectWidth, crossingAngle, calculatedNettingLength, crossingType } = params;

    console.log('计算当前系数，输入参数:', params);
    console.log('使用的规则:', rules);

    const applyFactorRules = (value, rules, defaultValue = 1.0, smallerIsHarder = false) => {
      if (value === undefined || value === null || !rules || rules.length === 0) {
        console.log(`应用规则失败: value=${value}, rules.length=${rules?.length}`);
        return defaultValue;
      }
      
      const sortedRules = [...rules].sort((a, b) => smallerIsHarder ? a.threshold - b.threshold : b.threshold - a.threshold);
      console.log(`排序后的规则 (smallerIsHarder=${smallerIsHarder}):`, sortedRules);
      
      for (const rule of sortedRules) {
        if (smallerIsHarder) {
          if (value < rule.threshold) {
            console.log(`匹配规则 (小于): value=${value} < threshold=${rule.threshold}, multiplier=${rule.multiplier}`);
            return rule.multiplier;
          }
        } else {
          if (value > rule.threshold) {
            console.log(`匹配规则 (大于): value=${value} > threshold=${rule.threshold}, multiplier=${rule.multiplier}`);
            return rule.multiplier;
          }
        }
      }
      
      console.log(`未匹配任何规则，使用默认值: ${defaultValue}`);
      return defaultValue;
    };

    const spanFactor = applyFactorRules(spanLength, rules.spanFactorRules, 1.0);
    const heightFactor = applyFactorRules(crossingHeight, rules.heightFactorRules, 1.0);
    const nettingFactor = applyFactorRules(calculatedNettingLength, rules.nettingFactorRules, 1.0);
    const angleFactor = applyFactorRules(crossingAngle, rules.angleFactorRules, 1.0, true);
    const widthFactor = applyFactorRules(crossedObjectWidth, rules.widthFactorRules, 1.0);
    const typeRule = rules.typeFactorMultipliers?.find(m => m.type === crossingType);
    const typeFactor = typeRule?.multiplier || 1.0;

    console.log('计算得到的各项系数:', {
      spanFactor, heightFactor, nettingFactor, angleFactor, widthFactor, typeFactor
    });

    // 计算综合系数及其计算过程
    const calculateResourceFactor = (resourceType) => {
      switch(resourceType) {
        case 'materials':
          return {
            value: heightFactor * widthFactor * nettingFactor,
            formula: `高度系数 × 宽度系数 × 封网系数`,
            calculation: `${heightFactor.toFixed(2)} × ${widthFactor.toFixed(2)} × ${nettingFactor.toFixed(2)}`,
            description: "物料需求主要受高度、宽度、封网长度等体积相关因素影响"
          };
        case 'personnel':
          return {
            value: heightFactor * spanFactor * typeFactor,
            formula: `高度系数 × 档距系数 × 类型系数`,
            calculation: `${heightFactor.toFixed(2)} × ${spanFactor.toFixed(2)} × ${typeFactor.toFixed(2)}`,
            description: "人员需求主要受高空作业难度、作业长度、跨越类型复杂性影响"
          };
        case 'equipment':
          return {
            value: heightFactor * widthFactor * spanFactor,
            formula: `高度系数 × 宽度系数 × 档距系数`,
            calculation: `${heightFactor.toFixed(2)} × ${widthFactor.toFixed(2)} × ${spanFactor.toFixed(2)}`,
            description: "工器具需求主要受高度、宽度、档距等作业范围影响"
          };
        case 'vehicles':
          return {
            value: widthFactor * nettingFactor * typeFactor,
            formula: `宽度系数 × 封网系数 × 类型系数`,
            calculation: `${widthFactor.toFixed(2)} × ${nettingFactor.toFixed(2)} × ${typeFactor.toFixed(2)}`,
            description: "车辆需求主要受运输量、场地条件影响"
          };
        case 'duration':
          return {
            value: (spanFactor + heightFactor + nettingFactor + angleFactor + widthFactor + typeFactor) / 6,
            formula: `(档距系数 + 高度系数 + 封网系数 + 角度系数 + 宽度系数 + 类型系数) ÷ 6`,
            calculation: `(${spanFactor.toFixed(2)} + ${heightFactor.toFixed(2)} + ${nettingFactor.toFixed(2)} + ${angleFactor.toFixed(2)} + ${widthFactor.toFixed(2)} + ${typeFactor.toFixed(2)}) ÷ 6`,
            description: "工时是所有因素的综合体现，采用平均值"
          };
        default:
          return { value: 1.0, formula: '', calculation: '', description: '' };
      }
    };

    return {
      individual: {
        spanFactor,
        heightFactor,
        nettingFactor,
        angleFactor,
        widthFactor,
        typeFactor
      },
      composite: {
        materialsFactor: calculateResourceFactor('materials'),
        personnelFactor: calculateResourceFactor('personnel'),
        equipmentFactor: calculateResourceFactor('equipment'),
        vehiclesFactor: calculateResourceFactor('vehicles'),
        durationFactor: calculateResourceFactor('duration')
      }
    };
  };

  const getActiveRuleIndex = (value, rules, smallerIsHarder = false) => {
    if (value === undefined || value === null || !rules || rules.length === 0) return -1;
    
    const sortedRules = [...rules].sort((a, b) => 
      smallerIsHarder ? a.threshold - b.threshold : b.threshold - a.threshold
    );
    
    for (let i = 0; i < sortedRules.length; i++) {
        // Find the original index of the current sorted rule to highlight correctly
        const originalIndex = rules.findIndex(r => r.threshold === sortedRules[i].threshold && r.multiplier === sortedRules[i].multiplier);
        if (smallerIsHarder) {
            if (value < sortedRules[i].threshold) {
                return originalIndex;
            }
        } else {
            if (value > sortedRules[i].threshold) {
                return originalIndex;
            }
        }
    }
    return -1;
  };
  
  // Use localFactors here
  const activeSpanRuleIndex = getActiveRuleIndex(crossingPoint?.spanLength, localFactors.spanFactorRules);
  const appliedSpanRule = activeSpanRuleIndex > -1 ? localFactors.spanFactorRules[activeSpanRuleIndex] : null;
  
  const activeHeightRuleIndex = getActiveRuleIndex(crossingPoint?.crossingHeight, localFactors.heightFactorRules);
  const appliedHeightRule = activeHeightRuleIndex > -1 ? localFactors.heightFactorRules[activeHeightRuleIndex] : null;

  const activeNettingRuleIndex = getActiveRuleIndex(scheme?.calculatedNettingLength, localFactors.nettingFactorRules);
  const appliedNettingRule = activeNettingRuleIndex > -1 ? localFactors.nettingFactorRules[activeNettingRuleIndex] : null;

  const activeAngleRuleIndex = getActiveRuleIndex(crossingPoint?.crossingAngle, localFactors.angleFactorRules, true);
  const appliedAngleRule = activeAngleRuleIndex > -1 ? localFactors.angleFactorRules[activeAngleRuleIndex] : null;

  const activeWidthRuleIndex = getActiveRuleIndex(crossingPoint?.crossedObjectWidth, localFactors.widthFactorRules);
  const appliedWidthRule = activeWidthRuleIndex > -1 ? localFactors.widthFactorRules[activeWidthRuleIndex] : null;

  const activeType = crossingPoint?.crossingType;

  const generateSmartRecommendation = async () => {
    if (!crossingPoint) return;

    setIsRecommending(true);
    try {
      const prompt = `作为电力工程专家，请基于以下跨越点数据推荐合理的工程量计算系数：

跨越点信息：
- 跨越类型：${crossingPoint.crossingType || '未知'}
- 档距：${crossingPoint.spanLength || 0}米
- 跨越高度：${crossingPoint.crossingHeight || 0}米
- 跨越物宽度：${crossingPoint.crossedObjectWidth || 0}米
- 交叉角度：${crossingPoint.crossingAngle || 90}度
- 难度等级：${crossingPoint.difficultyLevel || 'medium'}
- 封网长度：${scheme?.calculatedNettingLength || 0}米

请基于电力工程施工标准和实践经验，推荐以下系数规则：
1. 档距系数规则 (spanFactorRules)
2. 高度系数规则 (heightFactorRules)  
3. 封网系数规则 (nettingFactorRules)
4. 角度系数规则 (angleFactorRules)
5. 宽度系数规则 (widthFactorRules)
6. 跨越类型系数 (typeFactorMultipliers)

请提供具体的阈值和乘数建议，考虑安全性、经济性和施工可行性。`;

      const response = await InvokeLLM({
        prompt: prompt,
        addContextFromInternet: true,
        responseJsonSchema: {
          type: "object",
          properties: {
            spanFactorRules: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  threshold: { type: "number" },
                  multiplier: { type: "number" }
                }
              }
            },
            heightFactorRules: {
              type: "array", 
              items: {
                type: "object",
                properties: {
                  threshold: { type: "number" },
                  multiplier: { type: "number" }
                }
              }
            },
            nettingFactorRules: {
              type: "array",
              items: {
                type: "object", 
                properties: {
                  threshold: { type: "number" },
                  multiplier: { type: "number" }
                }
              }
            },
            angleFactorRules: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  threshold: { type: "number" },
                  multiplier: { type: "number" }
                }
              }
            },
            widthFactorRules: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  threshold: { type: "number" },
                  multiplier: { type: "number" }
                }
              }
            },
            typeFactorMultipliers: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  type: { type: "string" },
                  multiplier: { type: "number" }
                }
              }
            },
            reasoning: { type: "string" }
          }
        }
      });

      setLastRecommendation(response);
      
      if (response && typeof response === 'object') {
        setLocalFactors(prevFactors => {
          const updatedFactors = {
            ...prevFactors,
            ...response // Merge the AI recommendations into local state
          };
          onUpdate(updatedFactors); // Propagate the full updated factors object up
          return updatedFactors; // Return for local state update
        });
      }

    } catch (error) {
      console.error("生成智能推荐失败:", error);
      alert("生成智能推荐失败，请稍后重试");
    } finally {
      setIsRecommending(false);
    }
  };

  const handleFactorUpdate = (factorName, data) => {
    console.log(`更新工程系数字段 ${factorName}:`, data);
    
    // Update local state first
    setLocalFactors(prevFactors => {
      const updatedFactors = {
        ...prevFactors,
        [factorName]: data
      };
      // Propagate the full updated factors object up to the parent
      // This is crucial for the parent component to receive the latest state
      onUpdate(updatedFactors);
      return updatedFactors; // Return the new state for local use
    });
  };

  // Only check for scheme existence now, localFactors will be initialized by useEffect
  if (!scheme) {
    return (
      <Card>
        <CardContent className="p-6 text-center text-gray-500">
          <Info className="mx-auto w-8 h-8 mb-2" />
          <p>工程系数信息不可用。</p>
          <p className="text-sm mt-2">请先选择一个施工方案以加载默认系数。</p>
          {/* 调试信息 */}
          <div className="mt-4 p-2 bg-gray-100 rounded text-xs text-left">
            <p><strong>调试信息:</strong></p>
            <p>scheme存在: {scheme ? '是' : '否'}</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  // Use localFactors for rendering
  const factors = localFactors; 

  return (
    <TooltipProvider>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <SlidersHorizontal className="w-5 h-5 text-blue-600" />
            工程参数与系数配置
          </CardTitle>
          <p className="text-sm text-gray-500">
            下方系数用于动态计算方案的工时和资源。点击“编辑规则”可进行详细配置。
          </p>
          
          <div className="flex gap-2">
            <Button 
              onClick={generateSmartRecommendation} 
              disabled={isRecommending || !crossingPoint}
              variant="outline"
              size="sm text-white bg-purple-600 hover:bg-purple-700 "
            >
              {isRecommending ? (
                <>
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                  智能推荐中...
                </>
              ) : (
                <>
                  <Lightbulb className="w-4 h-4 mr-2" />
                  AI推荐系数
                </>
              )}
            </Button>
          </div>
        </CardHeader>
        
        <CardContent className="space-y-6">
          {/* 工程量系数预览 - 增加计算过程提示 */}
          {currentFactorPreview && (
            <Alert className="bg-blue-50 border-blue-200">
              <Calculator className="h-4 w-4 text-blue-700" />
              <AlertTitle className="text-blue-800">当前工程量系数预览</AlertTitle>
              <AlertDescription>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-3">
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-3 p-3 bg-white rounded-lg shadow-sm cursor-help">
                        <div className="p-2 bg-orange-100 rounded-full">
                          <Wrench className="h-4 w-4 text-orange-600" />
                        </div>
                        <div>
                          <div className="text-xs text-gray-600">物料系数</div>
                          <div className="text-lg font-bold text-gray-900">× {currentFactorPreview.composite.materialsFactor.value.toFixed(2)}</div>
                        </div>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-md">
                      <div className="space-y-2">
                        <p className="font-medium">{currentFactorPreview.composite.materialsFactor.description}</p>
                        <p className="text-sm"><strong>计算公式：</strong>{currentFactorPreview.composite.materialsFactor.formula}</p>
                        <p className="text-sm"><strong>计算过程：</strong>{currentFactorPreview.composite.materialsFactor.calculation}</p>
                        <p className="text-sm"><strong>最终结果：</strong>× {currentFactorPreview.composite.materialsFactor.value.toFixed(2)}</p>
                      </div>
                    </TooltipContent>
                  </Tooltip>

                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-3 p-3 bg-white rounded-lg shadow-sm cursor-help">
                        <div className="p-2 bg-green-100 rounded-full">
                          <Users className="h-4 w-4 text-green-600" />
                        </div>
                        <div>
                          <div className="text-xs text-gray-600">人员系数</div>
                          <div className="text-lg font-bold text-gray-900">× {currentFactorPreview.composite.personnelFactor.value.toFixed(2)}</div>
                        </div>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-md">
                      <div className="space-y-2">
                        <p className="font-medium">{currentFactorPreview.composite.personnelFactor.description}</p>
                        <p className="text-sm"><strong>计算公式：</strong>{currentFactorPreview.composite.personnelFactor.formula}</p>
                        <p className="text-sm"><strong>计算过程：</strong>{currentFactorPreview.composite.personnelFactor.calculation}</p>
                        <p className="text-sm"><strong>最终结果：</strong>× {currentFactorPreview.composite.personnelFactor.value.toFixed(2)}</p>
                      </div>
                    </TooltipContent>
                  </Tooltip>

                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-3 p-3 bg-white rounded-lg shadow-sm cursor-help">
                        <div className="p-2 bg-purple-100 rounded-full">
                          <Wrench className="h-4 w-4 text-purple-600" />
                        </div>
                        <div>
                          <div className="text-xs text-gray-600">工器具系数</div>
                          <div className="text-lg font-bold text-gray-900">× {currentFactorPreview.composite.equipmentFactor.value.toFixed(2)}</div>
                        </div>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-md">
                      <div className="space-y-2">
                        <p className="font-medium">{currentFactorPreview.composite.equipmentFactor.description}</p>
                        <p className="text-sm"><strong>计算公式：</strong>{currentFactorPreview.composite.equipmentFactor.formula}</p>
                        <p className="text-sm"><strong>计算过程：</strong>{currentFactorPreview.composite.equipmentFactor.calculation}</p>
                        <p className="text-sm"><strong>最终结果：</strong>× {currentFactorPreview.composite.equipmentFactor.value.toFixed(2)}</p>
                      </div>
                    </TooltipContent>
                  </Tooltip>

                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-3 p-3 bg-white rounded-lg shadow-sm cursor-help">
                        <div className="p-2 bg-cyan-100 rounded-full">
                          <Truck className="h-4 w-4 text-cyan-600" />
                        </div>
                        <div>
                          <div className="text-xs text-gray-600">车辆系数</div>
                          <div className="text-lg font-bold text-gray-900">× {currentFactorPreview.composite.vehiclesFactor.value.toFixed(2)}</div>
                        </div>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-md">
                      <div className="space-y-2">
                        <p className="font-medium">{currentFactorPreview.composite.vehiclesFactor.description}</p>
                        <p className="text-sm"><strong>计算公式：</strong>{currentFactorPreview.composite.vehiclesFactor.formula}</p>
                        <p className="text-sm"><strong>计算过程：</strong>{currentFactorPreview.composite.vehiclesFactor.calculation}</p>
                        <p className="text-sm"><strong>最终结果：</strong>× {currentFactorPreview.composite.vehiclesFactor.value.toFixed(2)}</p>
                      </div>
                    </TooltipContent>
                  </Tooltip>

                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-3 p-3 bg-white rounded-lg shadow-sm cursor-help">
                        <div className="p-2 bg-indigo-100 rounded-full">
                          <Clock className="h-4 w-4 text-indigo-600" />
                        </div>
                        <div>
                          <div className="text-xs text-gray-600">工时系数</div>
                          <div className="text-lg font-bold text-gray-900">× {currentFactorPreview.composite.durationFactor.value.toFixed(2)}</div>
                        </div>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-md">
                      <div className="space-y-2">
                        <p className="font-medium">{currentFactorPreview.composite.durationFactor.description}</p>
                        <p className="text-sm"><strong>计算公式：</strong>{currentFactorPreview.composite.durationFactor.formula}</p>
                        <p className="text-sm"><strong>计算过程：</strong>{currentFactorPreview.composite.durationFactor.calculation}</p>
                        <p className="text-sm"><strong>最终结果：</strong>× {currentFactorPreview.composite.durationFactor.value.toFixed(2)}</p>
                      </div>
                    </TooltipContent>
                  </Tooltip>
                </div>
                <p className="text-xs text-gray-500 mt-3">将鼠标悬浮在各系数卡片上可查看详细计算过程。修改下方系数时将自动更新。</p>
              </AlertDescription>
            </Alert>
          )}

          {lastRecommendation?.reasoning && (
            <Alert>
              <Lightbulb className="h-4 w-4" />
              <AlertTitle>AI推荐依据</AlertTitle>
              <AlertDescription>
                {lastRecommendation.reasoning}
              </AlertDescription>
            </Alert>
          )}
          
          <div>
            <h3 className="text-lg font-semibold text-gray-800 flex items-center gap-2 mb-4">
                <Calculator className="w-5 h-5 text-blue-600"/>
                工程量系数规则
            </h3>
            <div className="space-y-3">
             <FactorRulePopoverEditor
                title="档距系数 (spanFactor)"
                description="根据档距长度调整工时和资源。"
                unit="m"
                rules={factors.spanFactorRules || []}
                onUpdate={rules => handleFactorUpdate('spanFactorRules', rules)}
                activeRuleIndex={activeSpanRuleIndex}
                currentMultiplier={currentFactorPreview?.individual.spanFactor || 1.0}
                currentValue={crossingPoint?.spanLength}
                appliedRule={appliedSpanRule}
              />
              <FactorRulePopoverEditor
                title="高度系数 (heightFactor)"
                description="根据跨越高度调整高空作业相关工时和资源。"
                unit="m"
                rules={factors.heightFactorRules || []}
                onUpdate={rules => handleFactorUpdate('heightFactorRules', rules)}
                activeRuleIndex={activeHeightRuleIndex}
                currentMultiplier={currentFactorPreview?.individual.heightFactor || 1.0}
                currentValue={crossingPoint?.crossingHeight}
                appliedRule={appliedHeightRule}
              />
              <FactorRulePopoverEditor
                title="封网系数 (nettingFactor)"
                description="根据封网长度调整封网相关工时和资源。"
                unit="m"
                rules={factors.nettingFactorRules || []}
                onUpdate={rules => handleFactorUpdate('nettingFactorRules', rules)}
                activeRuleIndex={activeNettingRuleIndex}
                currentMultiplier={currentFactorPreview?.individual.nettingFactor || 1.0}
                currentValue={scheme?.calculatedNettingLength}
                appliedRule={appliedNettingRule}
              />
              <FactorRulePopoverEditor
                title="角度系数 (angleFactor)"
                description="交叉角度越小难度越大。"
                unit="°"
                isAngle={true}
                rules={factors.angleFactorRules || []}
                onUpdate={rules => handleFactorUpdate('angleFactorRules', rules)}
                activeRuleIndex={activeAngleRuleIndex}
                currentMultiplier={currentFactorPreview?.individual.angleFactor || 1.0}
                currentValue={crossingPoint?.crossingAngle}
                appliedRule={appliedAngleRule}
              />
              <FactorRulePopoverEditor
                title="宽度系数 (widthFactor)"
                description="根据被跨越物宽度调整跨越架等资源的规模。"
                unit="m"
                rules={factors.widthFactorRules || []}
                onUpdate={rules => handleFactorUpdate('widthFactorRules', rules)}
                activeRuleIndex={activeWidthRuleIndex}
                currentMultiplier={currentFactorPreview?.individual.widthFactor || 1.0}
                currentValue={crossingPoint?.crossedObjectWidth}
                appliedRule={appliedWidthRule}
              />
               <TypeFactorPopoverEditor
                title="跨越类型系数 (typeFactor)"
                description="为不同跨越类型设置基础难度乘数。"
                multipliers={factors.typeFactorMultipliers || []}
                onUpdate={multipliers => handleFactorUpdate('typeFactorMultipliers', multipliers)}
                activeType={activeType}
                currentMultiplier={currentFactorPreview?.individual.typeFactor || 1.0}
                currentValue={activeType}
              />
            </div>
          </div>
        </CardContent>
      </Card>
    </TooltipProvider>
  );
}
